package com.pug.gateway.service;


import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.stream.Stream;

/**
 * @author RenGaoshuai
 * @date 2023/5/12 17:54
 * @description
 */
@Service
public class AuthService {
    private static final String APPTOKEN = "appToken";
    public static final String AUTHORIZATION = "Authorization";
    public static final String BEARER = "Bearer";

    @Autowired
    private TokenService tokenService;

    /**
     * 不需要网关签权的url配置(/oauth,/open)
     * 默认/oauth开头是不需要的
     */

    private String ignoreUrls = "/oauth";


    public boolean ignoreAuthentication(String url) {
        return Stream.of(this.ignoreUrls.split(",")).anyMatch(ignoreUrl -> url.startsWith(StrUtil.trim(ignoreUrl)));
    }

    public boolean permission(String authentication, String url, String method) {

        // 如果请求未携带token信息, 直接权限
        if (StrUtil.isBlank(authentication) || !authentication.startsWith(BEARER)) {
            return Boolean.FALSE;
        }
        //token
        authentication = authentication.substring(BEARER.length());
        if (!tokenService.validateToken(authentication)) {
            return Boolean.FALSE;
        }

        //todo 调用鉴权服务判定是否有权限（目前均返回true）

        return Boolean.TRUE;
    }
}
